package com.user.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.user.entity.User;
import com.user.util.BaseDao;

public class UserDaoImpl {
	/*
	 * 添加用户方法
	 */
	public boolean addUser(User user){
		try{
			Connection con=BaseDao.getCon();
			PreparedStatement ps=con.prepareStatement("insert into users(username,password,email,address,hobby,photo) values(?,?,?,?,?,?)");
			ps.setString(1, user.getUsername());
			ps.setString(2, user.getPassword());
			ps.setString(3, user.getEmail());
			ps.setString(4, user.getAddress());
			ps.setString(5, user.getHobby());
			ps.setString(6, user.getPhoto());
			int rs = ps.executeUpdate();
			if(rs>0){
				return true;
			}else{
				return false;
			}
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
	}
	/*
	 * 验证该用户是否存在<根据username>
	 */
	public boolean isExist(String username){
		return findUserByUsername(username)==null?false:true;
	}
	/*
	 * 根据username查询相应用户
	 */
	public User findUserByUsername(String username){
		try{
			Connection con=BaseDao.getCon();
			PreparedStatement ps=con.prepareStatement("select * from users where username=?");
			ps.setString(1, username);
			ResultSet rs=ps.executeQuery();
			User user=null;
			while(rs.next()){
				user=new User();
				user.setId(rs.getInt(1));
				user.setUsername(rs.getString(2));
				user.setPassword(rs.getString(3));
				user.setEmail(rs.getString(4));
				user.setAddress(rs.getString(5));
				user.setHobby(rs.getString(6));
				user.setPhoto(rs.getString(7));
			}
			return user;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	/*
	 * 查询用户列表
	 */
	public List<User> findAll(){
		try{
			Connection con=BaseDao.getCon();
			PreparedStatement ps=con.prepareStatement("select * from users");
			ResultSet rs=ps.executeQuery();
			List<User> list=new ArrayList<User>();
			User user=null;
			while(rs.next()){
				user=new User();
				user.setId(rs.getInt(1));
				user.setUsername(rs.getString(2));
				user.setPassword(rs.getString(3));
				user.setEmail(rs.getString(4));
				user.setAddress(rs.getString(5));
				user.setHobby(rs.getString(6));
				user.setPhoto(rs.getString(7));
				list.add(user);
			}
			return list;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	

}
